package cn.tedu.net;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

//socket通信的服务器端
public class Server {
    public static void main(String[] args) throws IOException {
        //在指定的8888端口号处，等待客户端的连接
        ServerSocket server = new ServerSocket(8080);
        System.out.println("服务器已开启...");
        //接收客户端连接的请求，并建立通信通道socket
        Socket socket = server.accept();
        System.out.println("接收一个客户端的请求...");
        
        //开始通信
        BufferedInputStream in = new BufferedInputStream(socket.getInputStream());
//        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("C:\\Users\\tarena\\Downloads\\1.jpg")); 文件操作

        for (int i = 0; i < 5; i++) {
            char b = (char)in.read();
            System.out.print(b);
        }
//        int b = 0;
//        while ((b = in.read()) != -1){
//            System.out.print((char)b);
//        }

//        int b = 0;
//        while ((b = in.read()) != -1){   文件流的写入
//            out.write(b);
//        }
//        out.flush();

        //服务器给客户端发送数据
        BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
        System.out.println("请输入想要发送给服务器的数据：");
        String input = new Scanner(System.in).nextLine();
        out.write(input.getBytes());
        out.flush();

        //关闭socket
        server.close();
        socket.close();
        in.close();
        out.close();
    }
}
